var AV = require('leanengine');
var async = require('async');
var UserM = require('../models/modUser.js');
var ProM = require('../models/product');
var CouponM = require('../models/coupon');
//var job = require('./jobs.js');

//操作用户地址
var Product = AV.Object.extend("Product");
var Order = AV.Object.extend("Order");
var DOrder = AV.Object.extend("DiyOrder");
var TempOrder = AV.Object.extend("TempOrder");
var Giftcard = AV.Object.extend("Giftcard");
var Evaluate = AV.Object.extend("GoodsComment");
var FlowM = AV.Object.extend("OrderFlow");
var PointFlowM = AV.Object.extend("PointFlow");
var LimitBuyRecordM = AV.Object.extend("LimitBuyRecord");
var User = AV.Object.extend('_User');
var AmountFlowM = AV.Object.extend("AmountFlow");
var status = [[-1,-2,1000,1500,2000,2500,3000,4000,5000,6000,7000,8000,9000,9999],[1000,1500],[2000,2500,3000,4000,5000,6000,7000],[8000],[9000],[9999],[-1,-2]];

module.exports = {
    /*
    * 用户查询订单
    * Add By Jack 2015-08-24
    * params:
    * userid(用户 id)
    * index(0:全部订单, 1:未付款, 2:待收货, 3:待签收, 4:待评价, 5:已完成, 6:已撤销 )
    */
    getOrderList:function(userid,index){
        var query = new AV.Query(Order);
        var promise = new AV.Promise();
        if(userid){
            query.equalTo("uid", userid);
            //query.equalTo("type", index);
            //query.containedIn("type", [0,2,3,4,]);
            query.containedIn("status", status[index]);
            query.descending("updatedAt");
            query.limit(10);

            query.find().then(function(res){
                promise.resolve(res);
            });
            return promise;
        } else{
            return new AV.Promise.error({code:250});        //用户编号不能为空
        }
    },
    //我的全部订单
    getOrderListByAll:function(userid){
        return this.getOrderList(userid,0);
    },
    //我的待付款订单
    getOrderListByPay:function(userid){
        return this.getOrderList(userid,1);
    },
    //我的待收货订单
    getOrderListByReceived:function(userid){
        return this.getOrderList(userid,3);

    },
    //我的待评价订单
    getOrderListByEvaluation:function(userid){
        return this.getOrderList(userid,4);
    },
    //我的已完成订单
    getOrderListByComplete:function(userid){
        return this.getOrderList(userid,5);
    },
    /*
     * 创建新的订单
     * Add By Jack 2015-08-24
     * params:
     * orderInfo(object 对象)
     */
    addOrder:function(orderInfo){

        var order = new Order();
        var promise = new AV.Promise();
        console.log(orderInfo);
         order.save(orderInfo).then(function(res){
             console.log('生成订单1-1-1');
             require('./jobs').cancelOrder(res.id);
             promise.resolve(res);
         }).catch(function(err){
             promise.reject(err);
         });

        return promise;
    },
    /*
     * 获取临时订单
     * Add By James 2016-03-10
     * params:
     * orderInfo(object 对象)
     */
    getTempOrder:function(orderid){

        var query = new AV.Query(TempOrder);
        var promise = new AV.Promise();
        query.equalTo("orderid", orderid);
        query.equalTo("status", 1);
        query.find().then(function(res){
            promise.resolve(res);
        });
        return promise;
    },
    /*
     * 创建新的临时订单
     * Add By James 2016-03-08
     * params:
     * orderInfo(object 对象)
     */
    addTempOrder:function(orderInfo){
        var order = new TempOrder();
        var promise = new AV.Promise();
        order.save(orderInfo).then(function(res){
            require('./jobs').cancelTempOrder(res.id);
            promise.resolve(res);
        }).catch(function(err){
            promise.reject(err);
        });
        return promise;
    },
    /*
     * 查询订单详情
     * Add By Jack 2015-08-24
     * @param uid 用户id
     * @param orderid 订单编号
     */
    getOrderDetail:function(uid,orderid){

        if(!uid){
            return new AV.Promise.error({code:501});     //用户编号不能为空
        }

        if(!orderid){
            return new AV.Promise.error({code:502});     //订单编号不能为空
        }
        var query = new AV.Query(Order);
        var promise = new AV.Promise();
        query.equalTo('uid',uid);
        query.equalTo('orderid',orderid);
        query.find().then(function(res){
            var list = [];
            res.forEach(function(item){
                list.push( item.toJSON());
            });
            promise.resolve(list);
        });
        return promise;

    },
    /*
     * 撤销订单
     * Add By James 2015-09-11
     * @param objectId 订单ID
     */
    setOrderCancel:function(objectId){

        if(!objectId){
            return new AV.Promise.error({code:504});        //订单ID不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(Order);

        async.waterfall([
            function(callback){
                //根据objectId获取该对象
                query.get(objectId).then(function(res){
                    callback(null,res);
                }).catch(function(err){
                    callback({code:9999,reason:err});       //code:9999 系统错误
                });
            },
            function(res,callback){
                if(res.get('status') != 1000){
                    //订单状态非待付款，不能撤消
                    callback({code:9999,reason:'该订单状态非待付款，不能撤消'});       //code:9999 系统错误
                }else{
                    //获取到对象，则更新订单状态为-1
                    res.set('status',-1);
                    res.save().then(function(o){
                        o = o.toJSON();
                        callback(null,o.uid,o.balance,o.goods,o.couponId);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            },
            //如果该订单是余额+微信混合支付的话，则更新用户余额
            function(userid,balance,goods,couponId,callback){
                UserM.plusAmount(userid,balance).then(function(result){
                    callback(null,goods,couponId);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //更新商品库存
            function(goods,couponId,callback){
                for (var x in goods) {
                    ProM.updateInventory(goods[x].pid,goods[x].sid,goods[x].size).then(function(result){
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }

                callback(null,couponId);
            },
            //还原订单优惠券状态
            function(couponId,callback){
                if(!couponId){
                    callback(null,{code:0});
                }else{
                    CouponM.updateUserCoupon(couponId,0).then(function(result){
                        callback(null,{code:0});
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /*
     * 撤销订单
     * Add By James 2015-09-11
     * @param objectId 订单ID
     */
    setTempOrderCancel:function(objectId){

        if(!objectId){
            return new AV.Promise.error({code:504});        //订单ID不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(TempOrder);

        async.waterfall([
            function(callback){
                //根据objectId获取该对象
                query.get(objectId).then(function(res){
                    callback(null,res);
                }).catch(function(err){
                    callback({code:9999,reason:err});       //code:9999 系统错误
                });
            },
            function(res,callback){
                if(res.get('status') != 1){
                    //订单状态非待付款，不能撤消
                    callback({code:9999,reason:'该临时订单状态失效，不能撤消'});       //code:9999 系统错误
                }else{
                    //获取到对象，则更新订单状态为-1
                    res.set('status',-1);
                    res.save().then(function(o){
                        o = o.toJSON();
                        callback(null,o.goods);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            },
            //更新商品库存
            function(goods,callback){
                for (var x in goods) {
                    ProM.updateInventory(goods[x].pid,goods[x].sid,goods[x].size).then(function(result){
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }

                callback(null,{code:0});
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /*
     * 更新临时订单表的状态
     * Add By James 2016-03-09
     * @param objectId 订单ID
     */
    setTempOrderStatus:function(orderid){
        console.log('===========更新临时订单表的状态1');
        if(!orderid){
            return new AV.Promise.error({code:502});        //订单编号不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(TempOrder);

        async.waterfall([
            function(callback){
                console.log('===========更新临时订单表的状态2');
                //根据orderid获取该对象
                query.equalTo('orderid',orderid);
                query.equalTo('status',1);
                query.first().then(function(res){
                    callback(null,res);
                });
            },
            function(res,callback){
                console.log('===========更新临时订单表的状态3');
                if(!res || res.length<1){
                    console.log('===========更新临时订单表的状态4');
                    //获取不到对象
                    callback(null,{code:0});
                }else{
                    //获取到对象，则更新订单状态为2000
                    console.log('===========更新临时订单表的状态5');
                    res.set('status',-1);
                    res.save().then(function(){
                        console.log('===========更新临时订单表的状态6');
                        callback(null,{code:0});
                    }).catch(function(err){
                        console.log('===========更新临时订单表的状态7');
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            },
        ],function(err,result){
            console.log('===========更新临时订单表的状态8');
            if(err){
                console.log('===========更新临时订单表的状态9');
                promise.reject(err);
            }else{
                console.log('===========更新临时订单表的状态10');
                promise.resolve(result);
            }
        });
        return promise;
    },
    /*
     * 订单确认付款
     * Add By Jack 2015-08-24
     * params:
     * objectId(订单 id)
     */
    setOrderPay:function(payWay,uid,orderid){

        if(!uid){
            return new AV.Promise.error({code:501});        //用户编号不能为空
        }

        if(!orderid){
            return new AV.Promise.error({code:502});        //订单编号不能为空
        }

        if(!payWay){
            return new AV.Promise.error({code:503});        //付款方式不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(Order);

        async.waterfall([
            function(callback){
                //根据uid和orderid获取该对象
                query.equalTo('uid',uid);
                query.equalTo('orderid',orderid);
                query.equalTo('status',1000);
                query.first().then(function(res){
                    callback(null,res);
                });
            },
            function(res,callback){
                if(!res || res.length<1){
                    //获取不到对象
                    callback({code:9999,reason:'该订单已付款，无法付款'});       //code:9999 系统错误
                }else{
                    //获取到对象，则更新订单状态为2000
                    res.set('status',2000);
                    res.set('syncStatus',1);
                    res.set('payWay',payWay);
                    res.set('paytime',Date.parse(new Date()));
                    res.save().then(function(){
                        callback(null,{code:0});
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /*
     * 订单确认收货
     * Add By Jack 2015-08-24
     * @param uid 用户id
     * @param orderid 订单编号
     */
    setOrderConfirm:function(uid,orderid){

        if(!uid){
            return new AV.Promise.error({code:501});        //用户编号不能为空
        }

        if(!orderid){
            return new AV.Promise.error({code:502});        //订单编号不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(Order);

        async.waterfall([
            function(callback){
                //根据uid和orderid获取该对象
                query.equalTo('uid',uid);
                query.equalTo('orderid',orderid);
                query.equalTo('status',8000);
                query.first().then(function(res){
                    callback(null,res);
                });
            },
            function(res,callback){
                if(!res || res.length<1){
                    //获取不到对象
                    callback({code:9999,reason:'该订单还未派送，不能确认收货'});       //code:9999 系统错误
                }else{
                    //获取到对象，则更新订单状态为 9000
                    res.set('status',9000);
                    res.save().then(function(){
                        callback(null,res);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }
            },
            //更新用户积分
            function(res,callback){
                var point = res.get('point');
                if(point){
                    UserM.updatePoints(uid,point).then(function(result){
                        callback(null,point,result.ysjf,result.dqjf);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }else{
                    callback(null,0,0,0);
                }
            },
            //更新用户积分流水
            function(point,ysjf,dqjf,callback){
                if(point){
                    var pointFlow = new PointFlowM();
                    pointFlow.set('newpoint',point);
                    pointFlow.set('beforepoint',ysjf);
                    pointFlow.set('afterpoint',dqjf);
                    pointFlow.set('userid',uid);
                    pointFlow.set('content','通过订单'+orderid+'获得积分:'+point+'.');
                    pointFlow.save().then(function(result){
                        callback(null,{code:0});
                    }).catch(function(err){
                        callback({code:9999,reason:err});//code:9999 系统错误
                    });
                }else{
                    callback(null,{code:0});
                }
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /*
     * 评价订单
     * Add By Jack 2015-08-24
     * @param uid 用户id
     * @param orderid 订单编号
     */
    addEvaluation:function(data,user){
        var promise = new AV.Promise();
        var uid = user.uid ;
        var orderid = data.orderid ;
        console.log(uid);
        console.log(orderid);
        async.auto({
            getOrder:function(callback){
                //根据uid和orderid获取该对象
                var query = new AV.Query(Order);
                query.equalTo('uid',uid+'');
                query.equalTo('orderid',orderid);
                query.equalTo('status',9000);
                query.first().then(function(res){
                    callback(null,res);
                });
            },
            saveEva:['getOrder',function(callback,results){
                if(!results.getOrder || results.getOrder.length<1){
                    //获取不到对象
                    return callback({code:9999,reason:'该订单还未签收，不能评价'});       //code:9999 系统错误
                }else{
                    //需要循环获取data
                    async.eachSeries(data.content,function(value,callback1){
                        var eval = {} ;
                        eval['orderid'] = orderid ;
                        eval['uid'] = uid ;
                        eval['username'] = user.username ;
                        eval['phone'] = user.phone ;
                        eval['syncStatus'] = 1 ;
                        eval['status'] = 1 ;
                        eval['content'] = value.wenzi ;
                        eval['pid'] = value.pid ;
                        eval['pname'] = value.pname ;
                        eval['pname'] = value.pname ;
                        eval['score'] = parseInt(value.score||5);
                        var evaluate = new Evaluate();
                        evaluate.save(eval).then(function(){
                            callback1(null);
                        }).catch(function(err){
                            callback1(null);       //code:9999 系统错误
                        });
                    },function(){
                        callback(null);
                    })

                }
            }],
            updateProduct:['getOrder',function(callback,results){
                if(!results.getOrder || results.getOrder.length<1){
                    //获取不到对象
                    callback({code:9999,reason:'该订单还未签收，或者已评价成功'});       //code:9999 系统错误
                }else{
                    //需要循环获取data
                    async.eachSeries(data.content,function(value,callback1){
                        var query = new AV.Query(Product);
                        query.get(value.pid+'').then(function(pro){
                            if(pro){
                                pro.increment('commentCount');
                                pro.save().then(function(proN){
                                    callback1(null);
                                });
                            }else{
                                callback1(null);
                            }
                        });
                    },function(){
                        callback(null);
                    });
                }
            }],
            updateOrder:['saveEva',function(callback,results){
                //获取到对象，则更新订单状态为 9000
                results.getOrder.set('status',9999);
                results.getOrder.save().then(function(){
                    callback(null);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            }],
            //更新用户积分
            updateUser:['getOrder',function(callback,results){
                var userInfo = results.getOrder;
                var point = userInfo.get('point');
                if(point){
                    UserM.updatePoints(uid,point).then(function(result){
                        callback(null,{point:point,ysjf:result.ysjf,dqjf:result.dqjf});
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }else{
                    callback(null,{point:0,ysjf:0,dqjf:0});
                }
            }],
            //更新用户积分流水
            updatePointFlow:['updateUser','updateProduct','updateOrder',function(callback,results){
               var point = results.updateUser.point,
                   ysjf = results.updateUser.ysjf,
                   dqjf = results.updateUser.dqjf;
                if(point){
                    var pointFlow = new PointFlowM();
                    pointFlow.set('newpoint',point);
                    pointFlow.set('beforepoint',ysjf);
                    pointFlow.set('afterpoint',dqjf);
                    pointFlow.set('userid',uid);
                    pointFlow.set('content','通过订单'+orderid+'获得积分:'+point+'.');
                    pointFlow.save().then(function(result){
                        callback(null,{code:0});
                    }).catch(function(err){
                        callback({code:9999,reason:err});//code:9999 系统错误
                    });
                }else{
                    callback(null,{code:0});
                }
            }]
        },function(err,results){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(results.updatePointFlow);
            }
        });
        return promise;
    },
    addEvaluation_old:function(data,uid,orderid){

        if(!uid){
            return new AV.Promise.error({code:501});        //用户编号不能为空
        }

        if(!orderid){
            return new AV.Promise.error({code:502});        //订单编号不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(Order);

        async.waterfall([
            function(callback){
                //根据uid和orderid获取该对象
                query.equalTo('uid',uid);
                query.equalTo('orderid',orderid);
                query.equalTo('status',9000);
                query.first().then(function(res){
                    callback(null,res);
                });
            },
            function(res,callback){
                if(!res || res.length<1){
                    //获取不到对象
                    callback({code:9999,reason:'该订单还未签收，不能评价'});       //code:9999 系统错误
                }else{
                    var evaluate = new Evaluate();
                    evaluate.save(data).then(function(){
                        callback(null,res);
                    }).catch(function(err){
                        callback({code:9999,reason:err});       //code:9999 系统错误
                    });
                }
            },
            function(res,callback){
                //获取到对象，则更新订单状态为 9000
                res.set('status',9999);
                res.save().then(function(){
                    callback(null,res);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //更新用户积分
            function(res,callback){
                var point = res.get('point');
                if(point){
                    UserM.updatePoints(uid,point).then(function(result){
                        callback(null,point,result.ysjf,result.dqjf);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }else{
                    callback(null,0,0,0);
                }
            },
            //更新用户积分流水
            function(point,ysjf,dqjf,callback){
                if(point){
                    var pointFlow = new PointFlowM();
                    pointFlow.set('newpoint',point);
                    pointFlow.set('beforepoint',ysjf);
                    pointFlow.set('afterpoint',dqjf);
                    pointFlow.set('userid',uid);
                    pointFlow.set('content','通过订单'+orderid+'获得积分:'+point+'.');
                    pointFlow.save().then(function(result){
                        callback(null,{code:0});
                    }).catch(function(err){
                        callback({code:9999,reason:err});//code:9999 系统错误
                    });
                }else{
                    callback(null,{code:0});
                }
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /*
     * 微信支付回调接口
     * Add By Jack 2015-09-10
     * params:
     * objectId(订单 id)
     */
    notify:function(orderid,je,payWay){

        if(!orderid){
            return new AV.Promise.error({code:502});        //订单编号不能为空
        }

        if(!payWay){
            return new AV.Promise.error({code:503});        //付款方式不能为空
        }

        if(!je){
            return new AV.Promise.error({code:505});        //支付金额不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(Order);

        var uid;

        async.waterfall([
            function(callback){
                //根据uid和orderid获取该对象
                if(orderid.indexOf("-")<0){
                    //正常支付，有的订单是拆分订单，所以要用oid
                    if(orderid.indexOf("O")===0){
                        query.equalTo('oid',orderid);
                    }else{
                        query.equalTo('orderid',orderid);
                    }
                }else{
                    //重新支付,该拆的订单已拆分，所以要用orderid
                    query.equalTo('orderid',orderid);
                }

                //query.contains.equalTo('status',1500);
                query.containedIn('status',[1500,1000]);
                query.find().then(function(res){
                    callback(null,res);
                });
            },
            function(res,callback){
                if(!res || res.length<1){
                    //获取不到对象
                    callback({code:9999,reason:'该订单已付款，无法付款'});       //code:9999 系统错误
                }else{
                    res.forEach(function(r){
                        //获取到对象，则更新订单状态为2000
                        r.set('status',2000);
                        r.set('syncStatus',1);
                        r.set('paytime',new Date().getTime());
                        r.save().then(function(obj){
                            uid = obj.get('uid')
                        }).catch(function(err){
                            callback({code:9999,reason:err});   //code:9999 系统错误
                        });
                    });
                    callback(null,uid);
                }
            },
            //更新用户余额
            //function(userid,point,callback){
            //    UserM.minusAmount(userid,je).then(function(result){
            //        callback(null,userid,point);
            //    }).catch(function(err){
            //        callback({code:9999,reason:err});   //code:9999 系统错误
            //    });
            //},
            ////更新用户积分
            //function(userid,point,callback){
            //    UserM.updatePoints(userid,point).then(function(result){
            //        callback(null,userid);
            //    }).catch(function(err){
            //        callback({code:9999,reason:err});   //code:9999 系统错误
            //    });
            //},
            //生成流水信息
            function(userid,callback){

                var flow = new FlowM();
                flow.set('orderid',orderid);
                flow.set('amount',je/100);
                flow.set('paytime',new Date().getTime());
                flow.set('userid',userid);
                flow.set('content','使用微信支付'+je/100+'元.');
                flow.save().then(function(result){
                    callback(null,{code:0});       //添加购物车成功
                }).catch(function(err){
                    callback({code:9999,reason:err});//code:9999 系统错误
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /*
     * 微信支付回调接口
     * Add By Jack 2015-09-10
     * params:
     * objectId(订单 id)
     */
    dnotify:function(orderid,je,payWay){

        if(!orderid){
            return new AV.Promise.error({code:502});        //订单编号不能为空
        }

        if(!payWay){
            return new AV.Promise.error({code:503});        //付款方式不能为空
        }

        if(!je){
            return new AV.Promise.error({code:505});        //支付金额不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(DOrder);

        var uid;

        async.waterfall([
            function(callback){

                query.equalTo('orderid',orderid);


                query.containedIn('status',[1500,1000]);
                query.find().then(function(res){
                    callback(null,res);
                });
            },
            function(res,callback){
                if(!res || res.length<1){
                    //获取不到对象
                    callback({code:9999,reason:'该订单已付款，无法付款'});       //code:9999 系统错误
                }else{
                    res.forEach(function(r){
                        //获取到对象，则更新订单状态为2000
                        r.set('status',8000);
                        r.set('syncStatus',1);
                        r.set('paytime',new Date().getTime());
                        r.save().then(function(obj){
                            uid = obj.get('uid')
                        }).catch(function(err){
                            callback({code:9999,reason:err});   //code:9999 系统错误
                        });
                    });
                    callback(null,uid);
                }
            },
            //生成流水信息
            function(userid,callback){

                var flow = new FlowM();
                flow.set('orderid',orderid);
                flow.set('amount',je/100);
                flow.set('paytime',new Date().getTime());
                flow.set('userid',userid);
                flow.set('content','使用微信支付'+je/100+'元.');
                flow.save().then(function(result){
                    callback(null,{code:0});       //添加购物车成功
                }).catch(function(err){
                    callback({code:9999,reason:err});//code:9999 系统错误
                });
            }
        ],function(err,result){
            if(err){
                promise.reject(err);
            }else{
                promise.resolve(result);
            }
        });
        return promise;
    },
    /*
     * 订单重新付款
     * Add By James 2015-09-13
     * @param orderid 订单编号
     * @param payWay  支付方式
     */
    againPay:function(orderid,payway){
        console.log("====================订单重新付款========================");
        console.log(payway);
        console.log(orderid);
        if(!payway){
            return new AV.Promise.error({code:502});        //订单编号不能为空
        }

        if(!payway){
            return new AV.Promise.error({code:503});        //付款方式不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(Order);
        var str ;
        var balance = 0;

        if(payway =='ye_pay'){
            str = '余额支付';
        }else if(payway =='hdfk_pay'){
            str = '货到付款';
        }

        async.waterfall([
            function(callback){
                console.log("=======================1");
                //根据orderid获取该对象
                query.equalTo('orderid',orderid);
                query.containedIn('status',[1500,1000]);
                query.first().then(function(res){
                    callback(null,res);
                });
            },
            function(res,callback){
                if(!res || res.length<1){
                    console.log("=======================2");
                    //获取不到对象
                    callback({code:9990,reason:'该订单已付款，无法付款'});       //code:9999 系统错误
                }else{
                    console.log("=======================3");
                    var finalAmount = res.get('finalAmount');
                    var userid = res.get('uid');

                    UserM.getAmount(userid).then(function(result){
                        var amount = result.amount;
                        if(payway =='ye_pay' && amount < finalAmount ){
                            callback({code:9991,reason:'用户余额不足，无法付款'});       //code:9999 系统错误
                        }else{
                            callback(null,res);
                        }
                    })
                }
            },
            function(res,callback){
                console.log("=======================4");
                var finalAmount = res.get('finalAmount');

                //获取到对象，则更新订单状态为2000
                if(payway =='ye_pay'){
                    balance = finalAmount;
                }else if(payway =='hdfk_pay'){
                    balance = 0;
                }
                var old_str = res.get('description') ;
                var new_str = old_str.replace(res.get('payway'),str);
                console.log('==========代付款')
                console.log(res.get('payway'));
                console.log(old_str);
                console.log(str);
                console.log(new_str);
                console.log('==========代付款')
                res.set('status',2000);
                res.set('payway',str);
                res.set('syncStatus',1);
                res.set('online',0);
                res.set('onlinetype','');
                res.set('balance',balance);
                var jsontext = '[{"way":"'+str+'","pay":'+finalAmount+'}]';
                res.set('details',JSON.parse(jsontext));
                res.set('description',new_str);
                res.set('paytime',new Date().getTime());
                res.save().then(function(obj){
                    callback(null,obj);
                }).catch(function(err){
                    callback({code:9999,reason:err});   //code:9999 系统错误
                });
            },
            //更新用户余额
            function(obj,callback){
                console.log("=======================5");
                var userid = obj.get('uid');
                var balance = obj.get('balance');
                if(balance >0){
                    UserM.minusAmount(userid,balance*100).then(function(result){
                        callback(null,obj);
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                }else{
                    callback(null,obj);
                }
            },
            ////更新用户积分
            //function(obj,callback){
            //    var userid = obj.get('uid');
            //    var point = obj.get('point');
            //    UserM.updatePoints(userid,point).then(function(result){
            //        callback(null,obj);
            //    }).catch(function(err){
            //        callback({code:9999,reason:err});   //code:9999 系统错误
            //    });
            //},
            //生成流水信息
            function(obj,callback){
                console.log("=======================6");
                var userid = obj.get('uid');
                var finalAmount = obj.get('finalAmount');

                var flow = new FlowM();
                flow.set('orderid',orderid);
                flow.set('amount',finalAmount);
                flow.set('paytime',new Date().getTime());
                flow.set('userid',userid);
                flow.set('content','使用'+str+finalAmount+'元.');
                flow.save().then(function(result){
                    callback(null,{code:0});
                }).catch(function(err){
                    callback({code:9999,reason:err});//code:9999 系统错误
                });
            }
        ],function(err,result){
            console.log("=======================7");
            if(err){
                console.log("=======================8");
                console.log(err);
                promise.reject(err);
            }else{
                console.log("=======================9");
                promise.resolve(result);
            }
        });
        return promise;
    },
    //向LimitBuyRecord表中插入数据
    addToLimitRecord:function(uid,orderid,pid,sid,cid,actId){
        var promise = new AV.Promise();
        var query = new LimitBuyRecordM();
        query.set('cid',parseInt(cid));
        query.set('userid',uid+'');
        query.set('orderid',orderid+'');
        query.set('pid',parseInt(pid));
        query.set('aid',actId+'');
        query.set('sid',parseInt(sid));
        query.save().then(function(res){
            promise.resolve({code:0});
        }).catch(function(err){
            promise.reject({code:-1,});
        });
        return promise;
    },
    /*
     * 微信支付等待回调接口
     * Add By James 2015-12-28
     * params:
     * objectId(订单 id)
     */
    wxwait:function(orderid){
        console.log("===========================2");
        console.log(orderid);
        if(!orderid){
            return new AV.Promise.error({code:502});        //订单编号不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(Order);

        async.waterfall([
            function(callback){
                //根据uid和orderid获取该对象
                if(orderid.indexOf("-")<0){
                    //正常支付，有的订单是拆分订单，所以要用oid
                    if(orderid.indexOf("O")===0){
                        query.equalTo('oid',orderid);
                    }else{
                        query.equalTo('orderid',orderid);
                    }
                }else{
                    //重新支付,该拆的订单已拆分，所以要用orderid
                    query.equalTo('orderid',orderid);
                }

                query.equalTo('status',1000);
                query.find().then(function(res){
                    callback(null,res);
                });
            },
            function(res,callback){
                if(!res || res.length<1){
                    //获取不到对象
                    callback(null,{code:0});
                }else{
                    res.forEach(function(r){
                        //获取到对象，则更新订单状态为1500
                        r.set('status',1500);
                        r.save().then(function(obj){
                        }).catch(function(err){
                            callback({code:9999,reason:err});   //code:9999 系统错误
                        });
                    });
                    callback(null,{code:0});
                }
            }
        ],function(err,result){
            if(err){
                console.log("===========================21");
                promise.reject(err);
            }else{
                console.log("===========================22");
                promise.resolve(result);
            }
        });
        return promise;
    },
    /*
     * 充值卡充值
     * Add By James 2016-01-28
     * params:
     * km(充值卡密钥)
     */
    czkcz:function(km,timestamp,uid){

        if(!km){
            return new AV.Promise.error({code:510});        //卡密钥不能为空
        }

        var promise = new AV.Promise();
        var query = new AV.Query(Giftcard);

        async.waterfall([
            function(callback){
                //根据uid和orderid获取该对象

                query.equalTo('code',km);
                query.equalTo('status',1);
                query.equalTo('isBind',0);
                query.find().then(function(res){
                    callback(null,res);
                });
            },
            function(res,callback){

                if(!res || res.length<1){
                    //获取不到对象
                    console.log('==================a');
                    callback({code:511});   //code:511 卡密钥未激活
                }else{
                    console.log('&&&&&&&&&&&&&');
                    res.forEach(function(r){
                        //获取到对象，则更新订单状态为1500
                        r.set('isBind',1);
                        r.set('syncStatus',2);
                        r.set('bindUid',uid);
                        r.set('bindDate',timestamp+"");
                        r.save().then(function(obj){

                        }).catch(function(err){
                            callback({code:9999,reason:err});   //code:9999 系统错误
                        });
                    });
                    callback(null,res[0].get('amount'));
                }
            },
            //更新用户余额
            function(je,callback){
                console.log('==================b');
                var query = new AV.Query(User);
                var newAmount = 0 ;
                var oldAmount = 0 ;
                query.get(uid).then(function(res){
                    oldAmount = parseFloat(res.get('amount')) ;
                    newAmount = oldAmount+parseFloat(je) ;
                    res.save({amount:newAmount}).then(function(){
                        callback(null,{newAmount:newAmount,oldAmount:oldAmount,je:je});
                    }).catch(function(err){
                        callback({code:9999,reason:err});   //code:9999 系统错误
                    });
                });
            },
            //更新用户余额流水
            function(res,callback){
                console.log('==================c');
                var amountflow = new AmountFlowM();
                amountflow.set('newamount', parseFloat(res.je));
                amountflow.set('beforeamount',res.oldAmount);
                amountflow.set('afteramount',res.newAmount);
                amountflow.set('userid',uid);
                amountflow.set('content','通过密钥'+km+',账户余额充值'+parseFloat(res.je)+'元.');
                amountflow.save().then(function(result){
                    callback(null,{code:0});
                }).catch(function(err){
                    callback({code:9999,reason:err});//code:9999 系统错误
                });

            }
        ],function(err,result){
            if(err){
                console.log("===========================21");
                promise.reject(err);
            }else{
                console.log("===========================22");
                promise.resolve(result);
            }
        });
        return promise;
    }
};


